package net.neptech.task;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import net.neptech.model.dto.InstanceCopyDto;
import net.neptech.model.dto.node.CopyNode;
import net.neptech.model.dto.node.Node;
import net.neptech.node.NodeDataStoreFactory;
import net.neptech.service.RemoteService;
import net.neptech.strategy.node.AssignUserStrategyFactory;
import net.neptech.util.FlowableUtil;
import net.neptech.util.JsonUtil;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Saya
 * @Date 2025/8/24 18:11
 * @Description TODO
 **/
@Component
@RequiredArgsConstructor
public class CopyServiceTask implements JavaDelegate {
    private final RemoteService remoteService;
    @Override
    public void execute(DelegateExecution execution) {

        ExecutionEntityImpl entity = (ExecutionEntityImpl) execution;
        String nodeId = entity.getActivityId();
        String flowId = entity.getProcessDefinitionKey();

        Node node = NodeDataStoreFactory.getInstance().getNode(flowId, nodeId);

//发起人
        String rootUserId = FlowableUtil.getStartUserId(execution).toString();

        if (node != null) {

            Map<String, Object> variables = execution.getVariables();

            CopyNode copyNode = (CopyNode) node;

            Integer assignedType = copyNode.getAssignedType();

            List<String> userIdList = AssignUserStrategyFactory.getStrategy(assignedType).handle(node, rootUserId, variables);
            if (CollUtil.isNotEmpty(userIdList)) {
                //发送抄送任务
                InstanceCopyDto instanceCopyDto = new InstanceCopyDto();
                instanceCopyDto.setNodeTime(new Date());
                instanceCopyDto.setStartUserId(rootUserId);
                instanceCopyDto.setFlowId(flowId);
                instanceCopyDto.setInstanceId(execution.getProcessInstanceId());
                instanceCopyDto.setNodeId(nodeId);
                instanceCopyDto.setNodeName(node.getNodeName());
                instanceCopyDto.setFormData(JsonUtil.toJSONString(variables));
                instanceCopyDto.setUserIdList(userIdList);
                remoteService.saveCC(instanceCopyDto);
            }
        }
    }
}
